class NovelReader {
    constructor() {
        this.isPaused = false;
        this.settings = {
            fontSize: 14,
            speed: 60,
            hoverDelay: 200
        };
        
        this.init();
    }

    async init() {
        await this.loadNovelContent();
        this.bindEvents();
        this.loadSettings();
        this.applySettings();
    }

    async loadNovelContent() {
        try {
            const novelData = await window.electronAPI.ipcRenderer.invoke('get-novel-content');
            document.getElementById('novelContent').textContent = novelData.content;
        } catch (error) {
            console.error('加载小说内容失败:', error);
            document.getElementById('novelContent').textContent = '加载失败，请检查网络连接';
        }
    }

    updateNovelContent(novelData) {
        document.getElementById('novelContent').textContent = novelData.content;
        // 重新开始动画
        const novelContent = document.getElementById('novelContent');
        novelContent.style.animation = 'none';
        novelContent.offsetHeight; // 触发重排
        novelContent.style.animation = `scrollText ${this.settings.speed}s linear infinite`;
    }

    bindEvents() {
        // 鼠标悬停显示/隐藏标题栏
        const novelContainer = document.querySelector('.novel-container');
        const titleBar = document.querySelector('.title-bar');
        const body = document.body;
        let hideTimeout;

        // 鼠标进入主界面时显示背景和操作栏
        novelContainer.addEventListener('mouseenter', () => {
            clearTimeout(hideTimeout);
            body.classList.add('hover');
            titleBar.classList.add('show');
        });

        // 鼠标离开主界面时隐藏背景和操作栏
        novelContainer.addEventListener('mouseleave', () => {
            hideTimeout = setTimeout(() => {
                body.classList.remove('hover');
                titleBar.classList.remove('show');
            }, this.settings.hoverDelay);
        });

        // 鼠标悬停在标题栏上时保持显示
        titleBar.addEventListener('mouseenter', () => {
            clearTimeout(hideTimeout);
            body.classList.add('hover');
        });

        titleBar.addEventListener('mouseleave', () => {
            hideTimeout = setTimeout(() => {
                body.classList.remove('hover');
                titleBar.classList.remove('show');
            }, this.settings.hoverDelay / 2);
        });

        // 右键点击切换背景色（保持透明或显示背景）
        novelContainer.addEventListener('contextmenu', (e) => {
            e.preventDefault();
            body.classList.toggle('hover');
        });

        // 设置按钮
        document.getElementById('settingsBtn').addEventListener('click', () => {
            this.toggleSettings();
        });

        // 暂停按钮
        document.getElementById('pauseBtn').addEventListener('click', () => {
            this.togglePause();
        });

        // 关闭按钮
        document.getElementById('closeBtn').addEventListener('click', () => {
            window.close();
        });

        // 字体大小滑块
        const fontSizeSlider = document.getElementById('fontSizeSlider');
        const fontSizeValue = document.getElementById('fontSizeValue');
        fontSizeSlider.addEventListener('input', (e) => {
            this.settings.fontSize = parseInt(e.target.value);
            fontSizeValue.textContent = `${this.settings.fontSize}px`;
            this.applySettings();
        });

        // 滚动速度滑块
        const speedSlider = document.getElementById('speedSlider');
        const speedValue = document.getElementById('speedValue');
        speedSlider.addEventListener('input', (e) => {
            this.settings.speed = parseInt(e.target.value);
            speedValue.textContent = `${this.settings.speed}秒`;
            this.applySettings();
        });

        // 悬停延迟滑块
        const hoverDelaySlider = document.getElementById('hoverDelaySlider');
        const hoverDelayValue = document.getElementById('hoverDelayValue');
        hoverDelaySlider.addEventListener('input', (e) => {
            this.settings.hoverDelay = parseInt(e.target.value);
            hoverDelayValue.textContent = `${this.settings.hoverDelay}ms`;
            this.applySettings();
        });

        // 点击空白区域关闭设置面板
        document.addEventListener('click', (e) => {
            const settingsPanel = document.getElementById('settingsPanel');
            const settingsBtn = document.getElementById('settingsBtn');
            
            if (settingsPanel.classList.contains('show') && 
                !settingsPanel.contains(e.target) && 
                !settingsBtn.contains(e.target)) {
                settingsPanel.classList.remove('show');
            }
        });

        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            switch(e.key) {
                case ' ':
                    e.preventDefault();
                    this.togglePause();
                    break;
                case 'Escape':
                    this.hideSettings();
                    break;
                case 's':
                case 'S':
                    if (e.ctrlKey) {
                        e.preventDefault();
                        this.toggleSettings();
                    }
                    break;
                case 'h':
                case 'H':
                    if (e.ctrlKey) {
                        e.preventDefault();
                        this.toggleTitleBar();
                    }
                    break;
            }
        });

        // 鼠标滚轮控制滚动速度
        document.addEventListener('wheel', (e) => {
            if (e.ctrlKey) {
                e.preventDefault();
                const delta = e.deltaY > 0 ? -5 : 5;
                this.settings.speed = Math.max(30, Math.min(120, this.settings.speed + delta));
                speedSlider.value = this.settings.speed;
                speedValue.textContent = `${this.settings.speed}秒`;
                this.applySettings();
            }
        });
    }

    toggleSettings() {
        const settingsPanel = document.getElementById('settingsPanel');
        settingsPanel.classList.toggle('show');
    }

    hideSettings() {
        const settingsPanel = document.getElementById('settingsPanel');
        settingsPanel.classList.remove('show');
    }

    toggleTitleBar() {
        const titleBar = document.querySelector('.title-bar');
        titleBar.classList.toggle('show');
    }

    togglePause() {
        this.isPaused = !this.isPaused;
        const pauseBtn = document.getElementById('pauseBtn');
        const pauseOverlay = document.getElementById('pauseOverlay');
        const novelContent = document.getElementById('novelContent');

        if (this.isPaused) {
            pauseBtn.textContent = '继续';
            pauseOverlay.classList.add('show');
            novelContent.style.animationPlayState = 'paused';
        } else {
            pauseBtn.textContent = '暂停';
            pauseOverlay.classList.remove('show');
            novelContent.style.animationPlayState = 'running';
        }
    }

    loadSettings() {
        // 从本地存储加载设置
        const savedSettings = localStorage.getItem('novelReaderSettings');
        if (savedSettings) {
            this.settings = { ...this.settings, ...JSON.parse(savedSettings) };
        }

        // 更新UI
        document.getElementById('fontSizeSlider').value = this.settings.fontSize;
        document.getElementById('fontSizeValue').textContent = `${this.settings.fontSize}px`;
        
        document.getElementById('speedSlider').value = this.settings.speed;
        document.getElementById('speedValue').textContent = `${this.settings.speed}秒`;
        
        document.getElementById('hoverDelaySlider').value = this.settings.hoverDelay;
        document.getElementById('hoverDelayValue').textContent = `${this.settings.hoverDelay}ms`;
    }

    applySettings() {
        const novelContent = document.getElementById('novelContent');
        
        // 应用字体大小
        novelContent.style.fontSize = `${this.settings.fontSize}px`;
        
        // 应用滚动速度
        novelContent.style.animationDuration = `${this.settings.speed}s`;
        
        // 保存设置到本地存储
        localStorage.setItem('novelReaderSettings', JSON.stringify(this.settings));
    }

    // 获取窗口配置
    async getWindowConfig() {
        try {
            return await ipcRenderer.invoke('get-floating-config');
        } catch (error) {
            console.error('获取窗口配置失败:', error);
            return null;
        }
    }

    // 更新窗口配置
    async updateWindowConfig(config) {
        try {
            await ipcRenderer.invoke('update-floating-config', config);
        } catch (error) {
            console.error('更新窗口配置失败:', error);
        }
    }
}

// 初始化应用
let novelReader;
document.addEventListener('DOMContentLoaded', () => {
    novelReader = new NovelReader();
});

// 监听来自主进程的小说内容更新
window.electronAPI.ipcRenderer.on('novel-content-updated', (event, novelData) => {
    if (novelReader) {
        novelReader.updateNovelContent(novelData);
    }
});

// 允许右键菜单（用于切换背景色）

// 防止选择文本
document.addEventListener('selectstart', (e) => {
    e.preventDefault();
});